from Software_Set_ui import Ui_ProjectSettingsMain
from pipelineStarter_ui import Ui_MainWindow
from PyQt6.QtWidgets import QApplication,QInputDialog,QLineEdit,QMessageBox,QListWidgetItem,QMainWindow, QTreeWidgetItem,QHeaderView,QWidget, QHBoxLayout, QVBoxLayout, QToolButton, QSizePolicy, QPushButton, QGroupBox,QGridLayout 
import sys,os,json,subprocess,shutil
from PyQt6.QtGui import QIcon, QFont, QPixmap
from PyQt6.QtCore import QPoint, QRect, QSize, Qt
from PyQt6 import QtWidgets, QtCore, QtGui
from PyQt6.QtCore import QFile, QTextStream
from os import environ, listdir, makedirs, pathsep, startfile

# 获取当前文件的绝对路径
current_file = os.path.abspath(__file__)
# 获取当前文件所在的目录
current_dir = os.path.dirname(current_file)
# 构建 styles.css 的绝对路径
styles_css_path = os.path.join(current_dir, 'styles.css')
def loadStylesheet( file_path, widget):
    file = QFile(file_path)
    if not file.open(QFile.OpenModeFlag.ReadOnly | QFile.OpenModeFlag.Text):
        return
    stream = QTextStream(file)
    widget.setStyleSheet(stream.readAll())
    file.close()

class MainWindow(Ui_MainWindow, QMainWindow):
    Software ={}
    ProjecinfoPath = 'H:/QL_tool_file/Window_Tool/LogicalFile/SoftwareStarter/Projecinfo/'
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.initUI()

    def initUI(self):
        self.background_color()
        self.listWidget.itemSelectionChanged.connect(lambda *args: self.set_Projec_items())
        self.treeWidget.itemDoubleClicked.connect(lambda *args: self.on_item_double_clicked())
        for i in os.listdir(self.ProjecinfoPath):
            if i.endswith('.json'):
                ProjecName = i.split('.')[0]
                item = QListWidgetItem(ProjecName)
                font = QFont()
                font.setPointSize(20)
                item.setFont(font)
                self.listWidget.addItem(item)
    def set_Projec_items(self):
        self.software =''
        self.treeWidget.clear()
        selected_items = self.listWidget.selectedItems()   
        for item in selected_items:
            self.ProjecinfoPath
            with open(self.ProjecinfoPath + item.text() +'.json', 'r', encoding='utf8') as fp:
                self.json_data = json.load(fp)  # 读取json文件
                 
                for Software in self.json_data["Softwares"]:
                    print(Software["Software_Name"])
                    child2 = QTreeWidgetItem(self.treeWidget, [Software["Software_Name"]])
                    child2.setText(1, "Data 1")
    def on_item_double_clicked(self):
        proc_env = environ.copy()
        selected_items = self.treeWidget.selectedItems()
        for item in selected_items:
            # 获取选中项的数据
            text = item.text(0)  # 获取第一列的文本数据
            column_count = item.columnCount()  # 获取列数
            data = []
            for column in range(column_count):
                data.append(item.text(column))  # 获取每列的文本数据
            # 进一步处理获取到的数据
            #print("选中的文本:", text)
            #print("选中项的数据:", data)

        for Software in self.json_data["Softwares"]:
            if text == Software["Software_Name"]:
                launch_path = Software["Software_Path"]
                if launch_path:
                    for env_var in  Software["EnvironmentVariables"]:
                        print(env_var)
                        if env_var['Key'] in proc_env.keys():
                            proc_env[env_var['Key']] += pathsep + env_var['Value']
                        else:
                            proc_env[env_var['Key']] = env_var['Value']
            #print(proc_env)
            # 设置启动参数
            proc_args = []
            proc_args.append(launch_path)
            try:
                for arg in Software['Arguments']:
                    proc_args.append(arg)
            except KeyError:
                print('没有参数')
            print(proc_args)
            #print(proc_env)
            subprocess.Popen(proc_args, env= proc_env)
    def background_color(self):
        header = self.treeWidget.header()
        loadStylesheet(styles_css_path, header)
        loadStylesheet(styles_css_path, self.treeWidget)
        self.treeWidget.header().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)  # 自动调整列宽
        #header.setSectionResizeMode(1, QHeaderView.ResizeMode.Fixed)
        header.resizeSection(1, 200)

class SoftwareSet(Ui_ProjectSettingsMain, QMainWindow):
    ProjecinfoPath = 'H:/QL_tool_file/Window_Tool/LogicalFile/SoftwareStarter/Projecinfo/'
    def __init__(self):
        super(SoftwareSet, self).__init__()
        self.setupUi(self)
        self.initUI()

    def initUI(self):
        self.Project_WidgetItem_import()
        #self.Button_Clicked()
        self.scrollAreaWidgetContents.setVisible(self.ShotFile_info_widget.isVisible())
        #self.line_edit_list = []

    ##按钮激活
    #def Button_Clicked(self):
        ###设置按钮
        self.Project_Set_Bar.clicked.connect(self.__Project_Set_Visible)
        self.Project_Modile_Bar.clicked.connect(self.__Project_Modile_Visible)
        self.Shot_Set_Bar.clicked.connect(self.__Shot_Set_Visible)
        self.Launcher_Settings_Bar.clicked.connect(self.__Launcher_Settings_Visible)
        self.Project_Save.clicked.connect(self.__Project_Save_File)
        ###新建--删除
        self.Project_New.clicked.connect(self.__Project_New)
        self.Project_Del.clicked.connect(self.__Project_Del)

        self.NewModile_Button.clicked.connect(self.__New_Modile_lineEdit)
        self.New_Software_Button.clicked.connect(lambda *args: self.New_Software())
        self.Project_Set_listWidget.itemSelectionChanged.connect(lambda *args: self.on_selection_changed()) 
      
    #项目选择列表
    def Project_WidgetItem_import(self):
        for i in os.listdir(self.ProjecinfoPath):  # 循环读取路径下的文件并筛选输出
            new_item = QListWidgetItem(i.split(".")[0])
            new_item.setSizeHint(QtCore.QSize(180, 50))  # 设置按钮的高度为40
            font = new_item.font()
            font.setPointSize(14)  # 设置字体大小为14
            new_item.setFont(font)
            self.Project_Set_listWidget.addItem(new_item)
        
    #选择项目读取配置信息
    def on_selection_changed(self):
        self.scrollAreaWidgetContents.setVisible(self.ShotFile_info_widget.isEnabled())
        selected_items = self.Project_Set_listWidget.selectedItems()
        for item in selected_items:
            with open(self.ProjecinfoPath + item.text() +'.json', 'r', encoding='utf8') as fp:
                json_data = json.load(fp)  # 读取json文件
                self.Project_en_lineEdit.setText(json_data["Project_set"]["Project_en"])
                self.Project_cn_lineEdit.setText(json_data["Project_set"]["Project_cn"])
                self.Start_Time_lineEdit.setText(json_data["Project_set"]["Start_Time"])
                self.Frame_lineEdit.setText(json_data["Project_set"]["Frame"])
                self.ImageHeight_lineEdit.setText(json_data["Project_set"]["ImageHeight"])
                self.ImageWidth_lineEdit.setText(json_data["Project_set"]["ImageWidth"])
                self.ImageScale_lineEdit.setText(json_data["Project_set"]["ImageScale"])
                self.Project_local_Path_lineEdit.setText(json_data["Project_set"]["Project_local_Path"])
                self.Project_Network_Path_lineEdit.setText(json_data["Project_set"]["Project_Network_Path"])
                self.Project_assets_Path_lineEdit.setText(json_data["Project_set"]["Project_assets_Path"])

                self.read_Software_info_delete(self.Modile_List_Layout)
                
                Modile_set = json_data["Modile_set"]
                for Modile in range(len(Modile_set)):
                    self.__New_Modile_lineEdit()
                    self.NewModile_line_edit.setText(Modile_set[Modile]["ModileName"])


                Shot_set = json_data["Shot_set"]
                self.Set_lineEdit.setText(Shot_set["Set"])
                self.Set_Split_lineEdit.setText(Shot_set["Set_Split"])
                self.Events_lineEdit.setText(Shot_set["Events"])
                self.Events_Split_lineEdit.setText(Shot_set["Events_Split"])
                self.Lens_lineEdit.setText(Shot_set["Lens"])
                self.Lens_Split_lineEdit.setText(Shot_set["Lens_Split"])
                self.Class_lineEdit.setText(Shot_set["Class"])
                self.Class_Split_lineEdit.setText(Shot_set["Class_Split"])
                self.Version_lineEdit.setText(Shot_set["Version"])
                self.VersionNumber_lineEdit.setText(Shot_set["VersionNumber"])
                self.FileFormat_lineEdit.setText(Shot_set["FileFormat"])



                self.read_Software_info_delete(self.New_Starter_List_Layout)


                Softwares = json_data["Softwares"]
                for Software in Softwares:
                    self.read_Software_info(Software)

        

    def read_Software_info_delete(self,layout):
        #print(layout.objectName())
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            sublayout = item.layout()
            if widget is not None:
                widget.deleteLater()
            elif sublayout is not None:
                #self.delete_Launcher_layout(sublayout)
                self.read_Software_info_delete(sublayout)
    
             
    #读取软件信息
    def read_Software_info(self,Software):
        Software_Name = (Software["Software_Name"])
        Software_Path = (Software["Software_Path"])
        Software_Variables = (Software["EnvironmentVariables"])

        self.Starter_Basic_information_Layout = QtWidgets.QVBoxLayout()
        self.Starter_Basic_information_Layout.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetDefaultConstraint)
        self.Starter_Basic_information_Layout.setSpacing(6)
        self.Starter_Basic_information_Layout.setObjectName(Software_Name + "_Starter_Basic_information_Layout")
        self.Software_horizontal_Layout = QtWidgets.QHBoxLayout()
        self.Software_horizontal_Layout.setObjectName(Software_Name + "_Software_horizontal_Layout")
        self.Software_Name_Button = QtWidgets.QPushButton(Software_Name)
        self.Software_Name_Button.setMinimumSize(QtCore.QSize(0, 30))
        self.Software_Name_Button.setStyleSheet("background-color: rgb(24, 24, 24);")
        self.Software_Name_Button.setObjectName(Software_Name)
        self.Software_horizontal_Layout.addWidget(self.Software_Name_Button)
        self.New_Variable_Button = QtWidgets.QPushButton("新建")
        self.New_Variable_Button.setMinimumSize(QtCore.QSize(30, 30))
        self.New_Variable_Button.setMaximumSize(QtCore.QSize(30, 30))
        self.New_Variable_Button.setStyleSheet("background-color: rgb(24, 24, 24);")
        self.New_Variable_Button.setObjectName(Software_Name + "_New_Variable_Button")
        self.Software_horizontal_Layout.addWidget(self.New_Variable_Button)
        self.Software_Del_Button = QtWidgets.QPushButton("删除")
        self.Software_Del_Button.setMinimumSize(QtCore.QSize(30, 30))
        self.Software_Del_Button.setMaximumSize(QtCore.QSize(30, 30))
        self.Software_Del_Button.setStyleSheet("background-color: rgb(24, 24, 24);")
        self.Software_Del_Button.setObjectName(Software_Name + "_Software_Del_Button")
        self.Software_horizontal_Layout.addWidget(self.Software_Del_Button)
        self.Software_horizontal_Layout.setStretch(0, 1)
        self.Starter_Basic_information_Layout.addLayout(self.Software_horizontal_Layout)
        self.Software_path_Layout = QtWidgets.QHBoxLayout()
        self.Software_path_Layout.setObjectName(Software_Name + "_Software_path_Layout")
        self.Software_Path_LineEdit = QtWidgets.QLineEdit(self.New_Starter_Widget)
        self.Software_Path_LineEdit.setObjectName(Software_Name + "_Software_Path_LineEdit")
        self.Software_path_Layout.addWidget(self.Software_Path_LineEdit)
        self.Software_Path_Button = QtWidgets.QPushButton(self.New_Starter_Widget)
        self.Software_Path_Button.setStyleSheet("background-color: rgb(24, 24, 24);")
        self.Software_Path_Button.setObjectName(Software_Name + "_Software_Path_Button")
        self.Software_path_Layout.addWidget(self.Software_Path_Button)
        self.Starter_Basic_information_Layout.addLayout(self.Software_path_Layout)

        self.New_Starter_List_Layout.addLayout(self.Starter_Basic_information_Layout)




        self.Software_Path_LineEdit.setText(Software_Path)


        for count in range(len(Software_Variables)):
            self.read_Software_Variables_info(Software_Name,Software_Variables[count],str(count+3))

        self.New_Starter_List_Layout.addLayout(self.Starter_Basic_information_Layout)

        self.New_Variable_Button.clicked.connect(lambda *args: self.New_Variable())
        self.Software_Del_Button.clicked.connect(lambda *args: self.Software_Del())



    #读取软件环境变量
    def read_Software_Variables_info(self,Software_Name,Software_Variable,count):


        self.Variable_horizontal_Widget = QtWidgets.QWidget(self.New_Starter_Widget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.Variable_horizontal_Widget.sizePolicy().hasHeightForWidth())
        self.Variable_horizontal_Widget.setSizePolicy(sizePolicy)
        self.Variable_horizontal_Widget.setMinimumSize(QtCore.QSize(0, 23))
        self.Variable_horizontal_Widget.setMaximumSize(QtCore.QSize(16777215, 23))
        self.Variable_horizontal_Widget.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.DefaultContextMenu)
        self.Variable_horizontal_Widget.setLayoutDirection(QtCore.Qt.LayoutDirection.LeftToRight)
        self.Variable_horizontal_Widget.setObjectName(Software_Name +"_" + count + "_Variable_horizontal_Widget")
        self.Variable_horizontal_Layout = QtWidgets.QHBoxLayout(self.Variable_horizontal_Widget)
        self.Variable_horizontal_Layout.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetDefaultConstraint)
        self.Variable_horizontal_Layout.setContentsMargins(0, 0, 0, 0)
        self.Variable_horizontal_Layout.setSpacing(6)
        self.Variable_horizontal_Layout.setObjectName(Software_Name +"_" + count + "_Variable_horizontal_Layout")
        self.Variable_lineEdit = QtWidgets.QLineEdit(self.Variable_horizontal_Widget)
        self.Variable_lineEdit.setMinimumSize(QtCore.QSize(0, 23))
        self.Variable_lineEdit.setObjectName(Software_Name +"_" + count + "_Key")
        self.Variable_horizontal_Layout.addWidget(self.Variable_lineEdit)
        self.Value_lineEdit = QtWidgets.QLineEdit(self.Variable_horizontal_Widget)
        self.Value_lineEdit.setMinimumSize(QtCore.QSize(0, 23))
        self.Value_lineEdit.setObjectName(Software_Name +"_" + count + "_Value")
        self.Variable_horizontal_Layout.addWidget(self.Value_lineEdit)
        self.Del_Variable_Button = QtWidgets.QPushButton(self.Variable_horizontal_Widget)
        self.Del_Variable_Button.setMinimumSize(QtCore.QSize(23, 23))
        self.Del_Variable_Button.setMaximumSize(QtCore.QSize(23, 23))
        self.Del_Variable_Button.setStyleSheet("background-color: rgb(24, 24, 24);")
        self.Del_Variable_Button.setObjectName(Software_Name +"_" + count + "_Del_Variable_Button")
        self.Variable_horizontal_Layout.addWidget(self.Del_Variable_Button)
        self.Starter_Basic_information_Layout.addWidget(self.Variable_horizontal_Widget)


        self.Variable_lineEdit.setText(Software_Variable["Key"])
        self.Value_lineEdit.setText(Software_Variable["Value"])
 


        self.Del_Variable_Button.clicked.connect(lambda *args: self.delete_layout())


############################################################创建###################################################################################
    #创建项目
    def __Project_New(self):
        self.New_Project_Name, ok = QInputDialog.getText(self, "新建项", "请输入新项的名称:")
        if ok:
            new_item = QListWidgetItem(self.New_Project_Name)
            new_item.setSizeHint(QtCore.QSize(180, 50))  # 设置按钮的高度为40
            font = new_item.font()
            font.setPointSize(14)  # 设置字体大小为14
            new_item.setFont(font)
            self.Project_en_lineEdit.setText(self.New_Project_Name)
            self.Project_Set_listWidget.addItem(new_item)
            
            shutil.copyfile("H:/QL_tool_file/Window_Tool/Logical File/SoftwareStarter/TEXT.json","H:/QL_tool_file/Window_Tool/Logical File/SoftwareStarter/Projecinfo/" + self.New_Project_Name + ".json")



    ##创建新的项目模块
    def __New_Modile_lineEdit(self):
           
        for Modile_List in self.Project_Modile_info_widget.findChildren(QtWidgets.QVBoxLayout):
            # print(Modile_List.count())
            counts = Modile_List.count()+ 1
            print(counts)
            for count in range(counts):
                pass
            self.Modile_HB_Widget = QtWidgets.QWidget(self.Project_Modile_info_widget)
            self.Modile_HB_Widget.setMinimumSize(QtCore.QSize(0, 25))
            self.Modile_HB_Widget.setMaximumSize(QtCore.QSize(16777215, 25))
            self.Modile_HB_Widget.setObjectName(str(count) + "_Modile_HB_Widget")
            self.NewModile_HBLayout = QtWidgets.QHBoxLayout(self.Modile_HB_Widget)
            self.NewModile_HBLayout.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetMinAndMaxSize)
            self.NewModile_HBLayout.setContentsMargins(0, 0, 0, 0)
            self.NewModile_HBLayout.setSpacing(6)
            self.NewModile_HBLayout.setObjectName(str(count) + "_NewModile_HBLayout")
            self.NewModile_line_edit = QtWidgets.QLineEdit(self.Modile_HB_Widget)
            self.NewModile_line_edit.setMinimumSize(QtCore.QSize(0, 25))
            self.NewModile_line_edit.setObjectName("NewModile_line_edit")
            self.NewModile_HBLayout.addWidget(self.NewModile_line_edit)
            self.Del_modile_Button = QtWidgets.QPushButton(str(count))
            self.Del_modile_Button.setMinimumSize(QtCore.QSize(25, 25))
            self.Del_modile_Button.setMaximumSize(QtCore.QSize(25, 25))
            self.Del_modile_Button.setStyleSheet("background-color: rgb(24, 24, 24);")
            self.Del_modile_Button.setObjectName(str(count) + "_Del_modile_Button")
            self.NewModile_HBLayout.addWidget(self.Del_modile_Button)
            self.Modile_List_Layout.addWidget(self.Modile_HB_Widget)

            self.Del_modile_Button.clicked.connect(lambda *args: self.clicked_Del_modile_Layout())


    def clicked_Del_modile_Layout(self):
        sender = self.sender()
        Name = sender.objectName().split("_")
        Parent = []
        sublevel = []
        for Modile_List in self.Project_Modile_info_widget.findChildren(QtWidgets.QVBoxLayout):
            print(Modile_List.objectName())
            for  i in range(Modile_List.count()):
                Parent.append(Modile_List)
                item = Modile_List.itemAt(i).widget()
                if isinstance(item, QtWidgets.QWidget):
                    print(item.objectName())
                    if Name[0]+"_" in item.objectName():
                        sublevel.append(item)


        Parent[0].removeWidget(sublevel[0])
        sublevel[0].deleteLater()
                
            



    ##创建新的启动器
    def New_Software(self):
        text, ok = QInputDialog.getText(self, "启动器名称", "请输入新启动器名称:")
        if ok:


            self.Starter_Basic_information_Layout = QtWidgets.QVBoxLayout()
            self.Starter_Basic_information_Layout.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetDefaultConstraint)
            self.Starter_Basic_information_Layout.setSpacing(6)
            self.Starter_Basic_information_Layout.setObjectName(text + "_Starter_Basic_information_Layout")
            self.Software_horizontal_Layout = QtWidgets.QHBoxLayout()
            self.Software_horizontal_Layout.setObjectName(text + "_Software_horizontal_Layout")
            self.Software_Name_Button = QtWidgets.QPushButton(text)
            self.Software_Name_Button.setMinimumSize(QtCore.QSize(0, 30))
            self.Software_Name_Button.setStyleSheet("background-color: rgb(24, 24, 24);")
            self.Software_Name_Button.setObjectName(text)
            self.Software_horizontal_Layout.addWidget(self.Software_Name_Button)
            self.New_Variable_Button = QtWidgets.QPushButton("新建")
            self.New_Variable_Button.setMinimumSize(QtCore.QSize(30, 30))
            self.New_Variable_Button.setMaximumSize(QtCore.QSize(30, 30))
            self.New_Variable_Button.setStyleSheet("background-color: rgb(24, 24, 24);")
            self.New_Variable_Button.setObjectName(text + "_New_Variable_Button")
            self.Software_horizontal_Layout.addWidget(self.New_Variable_Button)
            self.Software_Del_Button = QtWidgets.QPushButton("删除")
            self.Software_Del_Button.setMinimumSize(QtCore.QSize(30, 30))
            self.Software_Del_Button.setMaximumSize(QtCore.QSize(30, 30))
            self.Software_Del_Button.setStyleSheet("background-color: rgb(24, 24, 24);")
            self.Software_Del_Button.setObjectName(text + "_Software_Del_Button")
            self.Software_horizontal_Layout.addWidget(self.Software_Del_Button)
            self.Software_horizontal_Layout.setStretch(0, 1)
            self.Starter_Basic_information_Layout.addLayout(self.Software_horizontal_Layout)
            self.Software_path_Layout = QtWidgets.QHBoxLayout()
            self.Software_path_Layout.setObjectName(text + "_Software_path_Layout")
            self.Software_Path_LineEdit = QtWidgets.QLineEdit(self.New_Starter_Widget)
            self.Software_Path_LineEdit.setObjectName(text + "_Software_Path_LineEdit")
            self.Software_path_Layout.addWidget(self.Software_Path_LineEdit)
            self.Software_Path_Button = QtWidgets.QPushButton(self.New_Starter_Widget)
            self.Software_Path_Button.setStyleSheet("background-color: rgb(24, 24, 24);")
            self.Software_Path_Button.setObjectName(text + "_Software_Path_Button")
            self.Software_path_Layout.addWidget(self.Software_Path_Button)
            self.Starter_Basic_information_Layout.addLayout(self.Software_path_Layout)

            self.New_Starter_List_Layout.addLayout(self.Starter_Basic_information_Layout)

      
            self.New_Variable_Button.clicked.connect(lambda *args: self.New_Variable())
            self.Software_Del_Button.clicked.connect(lambda *args: self.Software_Del())
        else:
            pass



    #创建新的启动器环境变量


    def New_Variable(self):
        sender = self.sender()
        clickedList = sender.objectName().split("_")[0]
        for NewLauncher in self.starter_settings_widget.findChildren(QtWidgets.QGridLayout):
                if "New_Starter_Layout" in NewLauncher.objectName():
                    for New_QVBoxLayout  in  NewLauncher.findChildren(QtWidgets.QVBoxLayout):
                        for Starter_Basic_information_Layout  in  New_QVBoxLayout.findChildren(QtWidgets.QVBoxLayout):
                            Starter_Basic_information_Layoutset = New_QVBoxLayout.findChild(QVBoxLayout,clickedList + "_Starter_Basic_information_Layout")
                            if Starter_Basic_information_Layout == Starter_Basic_information_Layoutset:
                                #print(Starter_Basic_information_Layout.objectName())
                                count = str(Starter_Basic_information_Layout.count()+1)
                                #print(count)
                              

                                self.Variable_horizontal_Widget = QtWidgets.QWidget(self.New_Starter_Widget)
                                sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Minimum, QtWidgets.QSizePolicy.Policy.Preferred)
                                sizePolicy.setHorizontalStretch(0)
                                sizePolicy.setVerticalStretch(0)
                                sizePolicy.setHeightForWidth(self.Variable_horizontal_Widget.sizePolicy().hasHeightForWidth())
                                self.Variable_horizontal_Widget.setSizePolicy(sizePolicy)
                                self.Variable_horizontal_Widget.setMinimumSize(QtCore.QSize(0, 23))
                                self.Variable_horizontal_Widget.setMaximumSize(QtCore.QSize(16777215, 23))
                                self.Variable_horizontal_Widget.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.DefaultContextMenu)
                                self.Variable_horizontal_Widget.setLayoutDirection(QtCore.Qt.LayoutDirection.LeftToRight)
                                self.Variable_horizontal_Widget.setObjectName(clickedList +"_" + count + "_Variable_horizontal_Widget")
                                self.Variable_horizontal_Layout = QtWidgets.QHBoxLayout(self.Variable_horizontal_Widget)
                                self.Variable_horizontal_Layout.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetDefaultConstraint)
                                self.Variable_horizontal_Layout.setContentsMargins(0, 0, 0, 0)
                                self.Variable_horizontal_Layout.setSpacing(6)
                                self.Variable_horizontal_Layout.setObjectName(clickedList +"_" + count + "_Variable_horizontal_Layout")
                                self.Variable_lineEdit = QtWidgets.QLineEdit(self.Variable_horizontal_Widget)
                                self.Variable_lineEdit.setMinimumSize(QtCore.QSize(0, 23))
                                self.Variable_lineEdit.setObjectName(clickedList +"_" + count + "_Key")
                                self.Variable_horizontal_Layout.addWidget(self.Variable_lineEdit)
                                self.Value_lineEdit = QtWidgets.QLineEdit(self.Variable_horizontal_Widget)
                                self.Value_lineEdit.setMinimumSize(QtCore.QSize(0, 23))
                                self.Value_lineEdit.setObjectName(clickedList +"_" + count + "_Value")
                                self.Variable_horizontal_Layout.addWidget(self.Value_lineEdit)
                                self.Del_Variable_Button = QtWidgets.QPushButton(self.Variable_horizontal_Widget)
                                self.Del_Variable_Button.setMinimumSize(QtCore.QSize(23, 23))
                                self.Del_Variable_Button.setMaximumSize(QtCore.QSize(23, 23))
                                self.Del_Variable_Button.setStyleSheet("background-color: rgb(24, 24, 24);")
                                self.Del_Variable_Button.setObjectName(clickedList +"_" + count + "_Del_Variable_Button")
                                self.Variable_horizontal_Layout.addWidget(self.Del_Variable_Button)
                                Starter_Basic_information_Layout.addWidget(self.Variable_horizontal_Widget)
        self.Del_Variable_Button.clicked.connect(lambda *args: self.delete_layout())
##########################################################删除########################################################################################
    #删除软件
    def Software_Del(self):
        sender = self.sender()
        clickedList = sender.objectName().split("_")[0]
        print(clickedList)
        #print(sender.objectName())
        '''
        Name = sender.objectName().split("_")
        Parent = []
        sublevel = []
        for Modile_List in self.starter_settings_widget.findChildren(QtWidgets.QVBoxLayout):

            print(Modile_List.objectName())
            for  i in range(Modile_List.count()):
                Parent.append(Modile_List)
                item = Modile_List.itemAt(i).widget()
                if isinstance(item, QtWidgets.QWidget):
                    print(item.objectName())
                    if Name[0]+"_" in item.objectName():
                        sublevel.append(item)


        Parent[0].removeWidget(sublevel[0])
        sublevel[0].deleteLater()'''

        
        layouts = self.starter_settings_widget.findChildren(QtWidgets.QGridLayout)
        #遍历 layouts 列表
        for layout in layouts:
            for New_Starter_List_Layout  in  layout.findChildren(QtWidgets.QVBoxLayout):
        
                if clickedList in New_Starter_List_Layout.objectName() and clickedList + "_Starter_Basic_information_Layout" == New_Starter_List_Layout.objectName():
                    self.delete_Launcher_layout(New_Starter_List_Layout)





    # 递归删除布局函数
    def delete_Launcher_layout(self,layout):
        print(layout.objectName())
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            sublayout = item.layout()
            if widget is not None:
                widget.deleteLater()
            elif sublayout is not None:
                self.delete_Launcher_layout(sublayout)
                
        parent = layout.parentWidget()
        if parent is not None:
            parent.layout().removeItem(layout)
        del layout
        
    ###删除网格布局内的横向布局
    def delete_layout(self):
        sender = self.sender()
        name = (sender.objectName().split("_"))
        #print(name[1])
        Parent = []
        sublevel = []
        for NewLauncher_QVBoxLayout in self.starter_settings_widget.findChildren(QtWidgets.QGridLayout):
                New_Starter_List_Layout = (NewLauncher_QVBoxLayout.findChild(QVBoxLayout,"New_Starter_List_Layout"))
                for child in New_Starter_List_Layout.children():
                    if isinstance(child, QVBoxLayout):
                        
                        #print(child.objectName())

                        if name[0] in child.objectName():
                            Parent.append(child)

                            layout_count = child.count()
                            for i in range(layout_count):
                                item = child.itemAt(i).widget()
                                if isinstance(item, QtWidgets.QWidget):
                                    print(item.objectName())
                                    print(name[0] + "_" + name[1] +"_Variable_horizontal_Widget")
                                    if name[0] + "_" + name[1] +"_Variable_horizontal_Widget" ==item.objectName():
                                        sublevel.append(item)
        Parent[0].removeWidget(sublevel[0])
        sublevel[0].deleteLater()
        print("555555555555555555555555555555")

    #删除项目
    def __Project_Del(self):
        selectedItems = self.Project_Set_listWidget.selectedItems()
        for item in selectedItems:
            row = self.Project_Set_listWidget.row(item)
            self.Project_Set_listWidget.takeItem(row)




    '''
    def show_context_menu(self, pos):
        sender = self.sender()  # 获取发送信号的对象
        menu = QMenu(sender)
        delete_action = QAction("删除", self)
        delete_action.triggered.connect(lambda: self.delete_line_edit(sender))
        menu.addAction(delete_action)
        menu.exec_(sender.mapToGlobal(pos))

    def delete_line_edit(self, line_edit):
        if line_edit in self.line_edit_list:
            line_edit.deleteLater()
            self.line_edit_list.remove(line_edit)'''


    ####################################################内容区域折叠#################################################################################
    ################################################################################################################################################

    def __Project_Set_Visible(self):
        # 切换内容区域的可见性
        self.Project_info_widget.setVisible(not self.Project_info_widget.isVisible())

    def __Project_Modile_Visible(self):
        # 切换内容区域的可见性
        self.Project_Modile_info_widget.setVisible(not self.Project_Modile_info_widget.isVisible())

    def __Shot_Set_Visible(self):
        # 切换内容区域的可见性
        self.ShotFile_info_widget.setVisible(not self.ShotFile_info_widget.isVisible())

    def __Launcher_Settings_Visible(self):
        self.New_Starter_Widget.setVisible(not self.New_Starter_Widget.isVisible())


    ####################################################设置保存#################################################################################
    ############################################################################################################################################

    def __Project_Save_File(self):
        if len(self.Project_en_lineEdit.text()) <= 0:
            # 创建消息框对象
            msg_box = QMessageBox()
            # 设置消息框的标题和文本内容
            msg_box.setWindowTitle("提示")
            msg_box.setText("需填写项目中文名！")
            msg_box.exec_()
        else:
            Project_info = {}
            Project_set ={}
            Project_set["Project_en"] = self.Project_en_lineEdit.text()
            Project_set["Project_cn"] = self.Project_cn_lineEdit.text()
            Project_set["Start_Time"] = self.Start_Time_lineEdit.text()
            Project_set["Frame"] = self.Frame_lineEdit.text()
            Project_set["ImageHeight"] = self.ImageHeight_lineEdit.text()
            Project_set["ImageWidth"] = self.ImageWidth_lineEdit.text()
            Project_set["ImageScale"] = self.ImageScale_lineEdit.text()
            Project_set["Project_local_Path"] = self.Project_local_Path_lineEdit.text()
            Project_set["Project_Network_Path"] = self.Project_Network_Path_lineEdit.text()
            Project_set["Project_assets_Path"] = self.Project_assets_Path_lineEdit.text()
            Project_info["Project_set"] = Project_set
            Project_ModileList = []
            line_edits = self.Project_Modile_info_widget.findChildren(QtWidgets.QLineEdit)
            for line_edit in line_edits:
                # 处理每一个lineEdit
                # print(line_edit.text())
                Project_Modile = {}
                Project_Modile["ModileName"] = line_edit.text()
                Project_ModileList.append(Project_Modile)
            Project_info["Modile_set"] = Project_ModileList

            # line_edits = self.Shot_Set_widget.findChildren(QtWidgets.QLineEdit)
            # for line_edit in line_edits:
            #    # 处理每一个lineEdit
            #    # print(line_edit.text())

            Project_ShotList = []
            Project_Shot = {}
            Project_Shot["Set"] = self.Set_lineEdit.text()
            Project_Shot["Set_Split"] = self.Set_Split_lineEdit.text()
            Project_Shot["Events"] = self.Events_lineEdit.text()
            Project_Shot["Events_Split"] = self.Events_Split_lineEdit.text()
            Project_Shot["Lens"] = self.Lens_lineEdit.text()
            Project_Shot["Lens_Split"] = self.Lens_Split_lineEdit.text()
            Project_Shot["Class"] = self.Class_lineEdit.text()
            Project_Shot["Class_Split"] = self.Class_Split_lineEdit.text()
            Project_Shot["Version"] = self.Version_lineEdit.text()
            Project_Shot["VersionNumber"] = self.VersionNumber_lineEdit.text()
            Project_Shot["FileFormat"] = self.FileFormat_lineEdit.text()
            # Project_ShotList.append(Project_Shot)
            Project_info["Shot_set"] = Project_Shot


            Softwares = {}
            Software_List = []
            for NewLauncher_QVBoxLayout in self.starter_settings_widget.findChildren(QtWidgets.QGridLayout):
                New_Starter_List_Layout = (NewLauncher_QVBoxLayout.findChild(QVBoxLayout,"New_Starter_List_Layout"))
                
                for child in New_Starter_List_Layout.children():
                    if isinstance(child, QVBoxLayout):
                        #print(child.objectName())
                        Softwareinfo = {}
                        
                        for SoftwareNameinfo in child.findChildren(QtWidgets.QHBoxLayout):
                            #print(SoftwareNameinfo)
                            for i in range(SoftwareNameinfo.count()):
                                widget = SoftwareNameinfo.itemAt(i).widget()

                                if isinstance(widget, QPushButton):
                                    if widget.text() == widget.objectName():

                                        Softwareinfo["Software_Name"] = widget.text()
                                if isinstance(widget, QLineEdit):
                                    if "_Software_Path_LineEdit" in widget.objectName():
                                        Softwareinfo["Software_Path"] = widget.text().replace("\\", "/")

                        Software_Variable_List = [] # 每次循环都创建一个新的空列表
                        layout_count = child.count()
                        for i in range(layout_count):
                            item = child.itemAt(i).widget()
                            if isinstance(item, QtWidgets.QWidget):
                                #print(item)
                                if "Variable_horizontal_Widget" in item.objectName() :
                                    QLineEditList = (item.findChildren(QtWidgets.QLineEdit))
                                    Variable = {}
                                    Variable["Key"] = QLineEditList[0].text()
                                    Variable["Value"] = QLineEditList[1].text()
                                    Software_Variable_List.append(Variable)
                            Softwareinfo["EnvironmentVariables"] = Software_Variable_List
                            #print(Softwareinfo)
                    if Softwareinfo:
                        Software_List.append(Softwareinfo)
            Project_info["Softwares"] = Software_List
            #print(Project_info)


            selected_items = self.Project_Set_listWidget.selectedItems()
            for select in selected_items:
                with open(self.ProjecinfoPath + select.text() +'.json','w') as fp:
                    json.dump(Project_info, fp, indent=4, sort_keys=False)

    def Open(self):
        self.show()

'''
if __name__ == "__main__":
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec()
'''
if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = MainWindow()
    child = SoftwareSet()
    main.show()

    main.actiontianjia.triggered.connect(child.Open)
    sys.exit(app.exec())


'''
if __name__ == '__main__':
    app = QApplication([]) if not QApplication.instance() else None
    MWin = Software_Set()
    for qt in QApplication.topLevelWidgets():
        print(qt.objectName())
        if qt.windowTitle() == u'aaaaaaaaaaaaaaaaaa':
            qt.close()
            app.quit()
    MWin.show()
    app.exec() if app else None'''

